# Django settings for cookmarks project.
# coding: utf-8

from os.path import join, dirname, abspath, pardir
import socket
import logging


PROJECT_ROOT = abspath(join(dirname(__file__), pardir))

# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConfigured

def get_env_setting(setting):
    """ Get the environment setting or return exception """
    try:
        return os.environ[setting]
    except KeyError:
        error_msg = "Set the %s env variable" % setting
        raise ImproperlyConfigured(error_msg)


SITE_NAME = 'cookmarks'
SITE_URL = '%s.dyndns.info' % SITE_NAME
SITE_VERSION = '0.1'

# MAIL
SERVER_EMAIL = "ovsinc@ya.ru"  # !!!
DEFAULT_FROM_EMAIL = "ovsinc@ya.ru"  # !!!
SYSTEM_EMAIL_PREFIX = "[%s]" % SITE_NAME

# для отправки кода активации
AUTH_USER_EMAIL_UNIQUE = True
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False

# for debuging email use: python -m smtpd -n -c DebuggingServer localhost:1025


# Set DEBUG = True if on the production server
if socket.gethostname() == SITE_URL:
    DEBUG = False
else:
    DEBUG = True

TEMPLATE_DEBUG = DEBUG

# Is this a development instance? Set this to True on development/master
# instances and False on stage/prod.
DEV = False

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'dev.db',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

# Place bcrypt first in the list, so it will be the default password hashing
# mechanism
PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [SITE_URL]

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Moscow'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'ru'

gettext_noop = lambda s: s
LANGUAGES = (
    ('en', gettext_noop('English')),
    ('ru', gettext_noop('Russian')),
)

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
#MEDIA_ROOT = ''
MEDIA_ROOT = join(PROJECT_ROOT, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
#STATIC_ROOT = ''
STATIC_ROOT = join(PROJECT_ROOT, 'static')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '_41s0*@j_yv72_ja3sd-st8bi0)thrix8$_l5zqjsi=^2)470+'

# SECURITY WARNING: keep the secret key used in production secret!
# Hardcoded values can leak through source control.
# This is an example method of getting the value from an environment setting.
# Uncomment to use, and then make sure you set the SECRET_KEY environment variable.
# This is good to use in production, and on services that support it such as Heroku.
#SECRET_KEY = get_env_setting('SECRET_KEY')


MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    #
    # http://wiki.linuxformat.ru/index.php/LXF107:Django
    #'django.middleware.http.ConditionalGetMiddleware',
    #'django.middleware.gzip.GZipMiddleware',
)

if DEBUG:
    MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)

ROOT_URLCONF = 'cookmarks.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cookmarks.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    join(PROJECT_ROOT, 'templates'),
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    'django.core.context_processors.csrf',
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    'yummy.context_processors.common',
    'django.core.context_processors.request',
    'libs.context_processors.site',
)

if DEBUG:
    TEMPLATE_CONTEXT_PROCESSORS += ('django.core.context_processors.debug',)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    # 'django.template.loaders.eggs.Loader',
)


INSTALLED_APPS = (
    'admin_tools',
    'admin_tools.theming',
    'admin_tools.menu',
    'admin_tools.dashboard',
    #
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    ## account and profiling
    'userprofiles',
    'userprofiles.contrib.accountverification',
    'userprofiles.contrib.emailverification',

    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',

    ## Third-party apps, patches, fixes
    # queues
    #'djcelery',

    ## css/js compress/ Do I need this now?
    'compressor',
    #'sekizai',

    ## forms design modify
    #'crispy_forms',
    #'widget_tweaks',

    # Database migrations
    'south',

    # image gallery
    'photologue',

    # WYSIWYG
    #'ckeditor',

    # avatars
    'avatar',

    # Application design, containing global templates.
    'apps.design',
    # profiling
    'apps.accounts',
    # carousel
    'apps.topcarousel',

    # cooking app
    'yummy',

)

if DEBUG:
    INSTALLED_APPS += (
        'debug_toolbar',
        #'debug_toolbar_user_panel',
        )

AUTH_PROFILE_MODULE = 'accounts.CustomUser'
CUSTOM_USER_MODEL = 'accounts.CustomUser'
LOGIN_REDIRECT_URL = 'my_profile'

# use auth beckend which decide use email or username in login
# add custom models
AUTHENTICATION_BACKENDS = (
    'apps.accounts.auth_backends.EmailOrUsernameModelBackend',
    'django.contrib.auth.backends.ModelBackend',
)


USERPROFILES_ACCOUNT_ACTIVATION_DAYS = 2 # кол-во дней для хранения кода активации
USERPROFILES_REGISTRATION_FORM = 'apps.accounts.forms.RegistrationProfileForm'
USERPROFILES_USE_PROFILE = False
USERPROFILES_PROFILE_FORM = 'apps.accounts.forms.ProfileForm'
USERPROFILES_CHECK_UNIQUE_EMAIL = True
USERPROFILES_DOUBLE_CHECK_PASSWORD = True
USERPROFILES_USE_ACCOUNT_VERIFICATION = True
USERPROFILES_ACCOUNT_VERIFICATION_DAYS = 2
# USERPROFILES_REGISTRATION_REDIRECT = 'home'  # use default
USERPROFILES_INLINE_PROFILE_ADMIN = False
USERPROFILES_EMAIL_ONLY = True
USERPROFILES_USE_EMAIL_VERIFICATION = True
# USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE = True  # conflicts with USERPROFILES_CHECK_UNIQUE_EMAIL

YUMMY_BASE_TEMPLATE = 'base.html'
#YUMMY_LISTING_PAGINATE_BY = ''
#YUMMY_GET_THUMBNAIL_FUNC = ''
#YUMMY_CACHE_OBJECT_FUNC = ''
#YUMMY_FUNC_QS_BY_RATING = ''
YUMMY_CATEGORY_ORDER = 'title'
YUMMY_RECIPESIZE = 'recipes'  # нужна фикстура для создания соответсвующего размера фоток

##PHOTOLOGUE
#PHOTOLOGUE_DIR = join(MEDIA_ROOT, 'recipes', 'images')
PHOTOLOGUE_DIR = join('recipes', 'images')
GALLERY_SAMPLE_SIZE = 15
PHOTOLOGUE_MAXBLOCK = 10 * 2 ** 10

## CKEDITOR
CKEDITOR_UPLOAD_PATH = PHOTOLOGUE_DIR

def custom_show_toolbar(request):
    """ Only show the debug toolbar to users with the superuser flag. """
    return request.user.is_superuser

if DEBUG:
    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
        #'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
        #'HIDE_DJANGO_SQL': True,
        #'TAG': 'body',
        #'SHOW_TEMPLATE_CONTEXT': True,
        #'ENABLE_STACKTRACES': True,
    }

    DEBUG_TOOLBAR_PANELS = (
        #'debug_toolbar_user_panel.panels.UserPanel',
        #'debug_toolbar.panels.version.VersionDebugPanel',
        'debug_toolbar.panels.timer.TimerDebugPanel',
        'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
        'debug_toolbar.panels.headers.HeaderDebugPanel',
        'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
        'debug_toolbar.panels.template.TemplateDebugPanel',
        'debug_toolbar.panels.sql.SQLDebugPanel',
        'debug_toolbar.panels.cache.CacheDebugPanel',
        'debug_toolbar.panels.logger.LoggingPanel',
    )

# Specify a custom user model to use
#AUTH_USER_MODEL = 'accounts.MyUser'

FILE_UPLOAD_PERMISSIONS = 0664

## Celery
# Uncomment these to activate and customize Celery:
# CELERY_ALWAYS_EAGER = False  # required to activate celeryd
# BROKER_HOST = 'localhost'
# BROKER_PORT = 5672
# BROKER_USER = 'django'
# BROKER_PASSWORD = 'django'
# BROKER_VHOST = 'django'
# CELERY_RESULT_BACKEND = 'amqp'

# bleach
'''
# Which HTML tags are allowed
BLEACH_ALLOWED_TAGS = ['p', 'b', 'i', 'u', 'em', 'strong', 'a']

# Which HTML attributes are allowed
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'style']

# Which CSS properties are allowed in 'style' attributes (assuming
# style is an allowed attribute)
BLEACH_ALLOWED_STYLES = [
    'font-family', 'font-weight', 'text-decoration', 'font-variant']

# Strip unknown tags if True, replace with HTML escaped characters if
# False
BLEACH_STRIP_TAGS = True

# Strip comments, or leave them in.
BLEACH_STRIP_COMMENTS = False

# Use the CKEditorWidget for bleached HTML fields
BLEACH_DEFAULT_WIDGET = 'ckeditor.widgets.CKEditorWidget'
'''

INTERNAL_IPS = (
    '127.0.0.1',
)

# Enable these options for memcached
#CACHE_BACKEND= "memcached://127.0.0.1:11211/"
#CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True
if DEBUG:
    CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
else:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',
            'TIMEOUT': 60 * 60 * 24,
            'KEY_PREFIX':  SITE_NAME,
            'VERSION': SITE_VERSION
        }
    }


# Set this to true if you use a proxy that sets X-Forwarded-Host
#USE_X_FORWARDED_HOST = False


REGISTRATION_BACKENDS = {
    'default': 'registration.backends.default.Backend',
    #'other': 'myapp.backends.MyBackend',
}


## Log settings
LOG_LEVEL = logging.INFO
HAS_SYSLOG = True
SYSLOG_TAG = "http_app_%s" % SITE_NAME  # Make this unique to your project.
# Remove this configuration variable to use your custom logging configuration
LOGGING_CONFIG = None

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'base': {
            'handlers': ['console'],
            'filters': ['require_debug_true'],
            'level': "DEBUG"
        },
        'cookmarks': {
            'handlers': ['console'],
            'filters': ['require_debug_true'],
            'level': "DEBUG"
        },
    }
}

# MY SETTINGS
BOOTSTRAP_THEME = 'united'
#BOOTSTRAP_THEME = 'journal'

# Common Event Format logging parameters
#CEF_PRODUCT = 'projectname'
#CEF_VENDOR = 'Your Company'
#CEF_VERSION = '0'
#CEF_DEVICE_VERSION = '0'

try:
    from local_settings import *
except ImportError:
    pass
